﻿using AutoMapper;
using MediatR;
using MediatR.Pipeline;
using Traceability.Commont.Domains;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.Infrastructures.Interfaces;

namespace Traceability.Api.Applications.Permissionts
{
    public class PermissionsCartsHander : IRequestHandler<PermissionsCartsCommand, Resqults<CardsDTo>>
    {
        private readonly IBateRepository<Permissions> permission;
        private readonly IMapper mapper;

        public PermissionsCartsHander(IBateRepository<Permissions> permission, IMapper mapper)
        {
            this.permission = permission;
            this.mapper = mapper;
        }

        public async Task<Resqults<CardsDTo>> Handle(PermissionsCartsCommand request, CancellationToken cancellationToken)
        {
            var result = new Resqults<CardsDTo>();
            var list = permission.GetAll().Where(x => x.Pid == 0).ToList();
            List<CardsDTo> res = new List<CardsDTo>();
            foreach (var item in list)
            {
                var CardsDTo = new CardsDTo();
                CardsDTo.Label = item.PermissionsName;
                CardsDTo.Value = item.PermissionsId;
                CardsDTo.Children = GetPermissions(item.PermissionsId);
                res.Add(CardsDTo);
            }
            result.Code = 1;
            result.Messges = "ok";
            result.Date = res;
            return result;
        }

        public List<CardsDTo> GetPermissions(int id)
        {
            var list = permission.GetAll().Where(x => x.Pid == id).ToList();
            List<CardsDTo> res = new List<CardsDTo>();
            foreach (var item in list)
            {
                var CardsDTo = new CardsDTo();
                CardsDTo.Label = item.PermissionsName;
                CardsDTo.Value = item.PermissionsId;
                CardsDTo.Children = GetPermissions(item.PermissionsId);
                res.Add(CardsDTo);
            }
            return res;
        }
    }
}
